<template>
  <div>
    <div
      v-for="(row, i) in valueModel"
      :key="element.key + '_' + i"
      style="display: flex; align-items: center"
    >
      <u-row
        :key="row.key"
        style="flex: 1"
        type="flex"
        :gutter="element.options.gutter ?? 0"
        :justify="element.options.justify"
        :align="element.options.align"
      >
        <template v-if="element.fieldCode === fixedCombinationFieldCode.piInfo">
          <u-col :span="8">
            <u-form-item
              :colon="false"
              :name="fixedCombinationCode.piInfo.piMajor + '_' + i"
              :rules="{
                required: true,
                validator: checkPiMajor,
                trigger: 'change',
              }"
            >
              <template #label>
                本中心承担的专业
                <a-tooltip>
                  <template #title>找不到专业？请联系机构老师</template>
                  <u-icon
                    name="question-circle-fill"
                    color="#0177fd"
                    size="24"
                  ></u-icon>
                  <!-- <Icon class="cursor-pointer" size="20" color="#999"
                    ><QuestionCircle16Filled
                  /></Icon> -->
                </a-tooltip>
              </template>
              <template v-if="disabled">
                {{ row.profession.label || '--' }}
                <span
                  v-if="approvalPermission"
                  class="project-num ml-4 cursor-pointer"
                  @click="gotoClick('majorIdList', row.profession.value)"
                  >在研项目{{ majorObj[row.profession.value] || 0 }}个</span
                >
              </template>
              <template v-else>
                <a-select
                  v-model:value="row.profession.value"
                  :size="config.size"
                  :allow-clear="true"
                  :style="{ width: '100%' }"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                  show-search
                  :filter-option="false"
                  :field-names="{ label: 'majorName', value: 'majorId' }"
                  :options="professionArrRow[row.key]"
                  @search="
                    (val) => {
                      handleSearchProfession(row.key, val, i);
                    }
                  "
                  @change="
                    (val) => {
                      changeProfession(row.key, val, i);
                    }
                  "
                >
                </a-select>
              </template>
            </u-form-item>
          </u-col>
          <a-col :span="8">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.piInfo.piName + '_' + i"
              :rules="{
                required: true,
                validator: checkPiName,
                trigger: 'change',
              }"
            >
              <template #label> 本中心主要研究者 </template>
              <template v-if="disabled">
                {{ row.pi.fullLabel || '--' }}

                <span
                  v-if="approvalPermission"
                  class="project-num ml-4 cursor-pointer"
                  @click="gotoClick('pi', row.pi.label)"
                  >在研项目{{ piObj[row.pi.value] || 0 }}个</span
                >
              </template>
              <template v-else>
                <a-select
                  v-model:value="row.pi.value"
                  :size="config.size"
                  :allow-clear="true"
                  :style="{ width: '100%' }"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                  show-search
                  :filter-option="false"
                  @search="
                    (val) => {
                      handleSearchPi(row.key, val, i);
                    }
                  "
                  @change="
                    (val) => {
                      changePi(row.key, val, i);
                    }
                  "
                >
                  <a-select-option
                    v-for="piOpt of piArrRow[row.key]"
                    :key="piOpt.userId"
                    :value="piOpt.userId"
                    :label="piOpt.name"
                  >
                    {{ piOpt.name + '（' + piOpt.mobile + ')' }}
                  </a-select-option>
                </a-select>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.piInfo.piTitle + '_' + i"
              :rules="{
                required: true,
                validator: checkPiTitle,
                trigger: 'blur',
              }"
            >
              <template #label> 本中心主要研究者职称 </template>
              <template v-if="disabled">
                {{ row.titleType || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value="row.titleType"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
        </template>
        <template
          v-else-if="
            element.fieldCode === fixedCombinationFieldCode.sponsorInfo
          "
        >
          <a-col :span="8">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.sponsorInfo.sponsorOrg + '_' + i"
              :rules="{
                required: true,
                validator: checkSponsorOrg,
                trigger: 'change',
              }"
            >
              <template #label>
                申办方
                <a-tooltip>
                  <template #title>找不到申办方？请联系客服更新</template>
                  <u-icon
                    name="question-circle-fill"
                    color="#0177fd"
                    size="24"
                  ></u-icon>
                  <!-- <Icon class="cursor-pointer" size="20" color="#999"
                    ><QuestionCircle16Filled
                  /></Icon> -->
                </a-tooltip>
              </template>
              <template v-if="disabled">
                {{ row.orgInfo.label || '--' }}
              </template>
              <template v-else>
                <a-select
                  v-model:value="row.orgInfo.value"
                  :size="config.size"
                  :allow-clear="true"
                  :style="{ width: '100%' }"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                  show-search
                  :filter-option="false"
                  :field-names="{ label: 'orgName', value: 'orgId' }"
                  :options="orgArrRow[row.key]"
                  @search="
                    (val) => {
                      handleSearchOrg(row.key, val, i);
                    }
                  "
                  @change="
                    (val) => {
                      changeOrg(row.key, val, i);
                    }
                  "
                >
                </a-select>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.sponsorInfo.sponsorContact + '_' + i"
            >
              <template #label> 申办方联系人 </template>
              <template v-if="disabled">
                {{ row.contactName || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value="row.contactName"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.sponsorInfo.sponsorPhone + '_' + i"
            >
              <template #label> 申办方联系方式 </template>
              <template v-if="disabled">
                {{ row.contactPhone || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value="row.contactPhone"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
        </template>
        <template
          v-else-if="element.fieldCode === fixedCombinationFieldCode.croInfo"
        >
          <a-col :span="8">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.croInfo.croOrg + '_' + i"
            >
              <template #label>
                CRO
                <a-tooltip>
                  <template #title>找不到CRO？请联系客服更新</template>
                  <u-icon
                    name="question-circle-fill"
                    color="#0177fd"
                    size="24"
                  ></u-icon>
                  <!-- <Icon class="cursor-pointer" size="20" color="#999"
                    ><QuestionCircle16Filled
                  /></Icon> -->
                </a-tooltip>
              </template>
              <template v-if="disabled">
                {{ row.orgInfo.label || '--' }}
              </template>
              <template v-else>
                <a-select
                  v-model:value="row.orgInfo.value"
                  :size="config.size"
                  :allow-clear="true"
                  :style="{ width: '100%' }"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                  show-search
                  :filter-option="false"
                  :field-names="{ label: 'orgName', value: 'orgId' }"
                  :options="orgArrRow[row.key]"
                  @search="
                    (val) => {
                      handleSearchOrg(row.key, val, i);
                    }
                  "
                  @change="
                    (val) => {
                      changeOrg(row.key, val, i);
                    }
                  "
                >
                </a-select>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.croInfo.croContact + '_' + i"
            >
              <template #label> CRO联系人 </template>
              <template v-if="disabled">
                {{ row.contactName || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value="row.contactName"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.croInfo.croPhone + '_' + i"
            >
              <template #label> CRO联系方式 </template>
              <template v-if="disabled">
                {{ row.contactPhone || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value="row.contactPhone"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
        </template>
        <template
          v-else-if="element.fieldCode === fixedCombinationFieldCode.smoInfo"
        >
          <a-col :span="8">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.smoInfo.smoOrg + '_' + i"
            >
              <template #label>
                SMO
                <a-tooltip>
                  <template #title>找不到SMO？请联系客服更新</template>
                  <!-- <Icon class="cursor-pointer" size="20" color="#999"><QuestionCircle16Filled /></Icon> -->
                  <u-icon
                    name="question-circle-fill"
                    color="#0177fd"
                    size="24"
                  ></u-icon>
                </a-tooltip>
              </template>
              <template v-if="disabled">
                {{ row.orgInfo.label || '--' }}
              </template>
              <template v-else>
                <a-select
                  v-model:value="row.orgInfo.value"
                  :size="config.size"
                  :allow-clear="true"
                  :style="{ width: '100%' }"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                  show-search
                  :filter-option="false"
                  :field-names="{ label: 'orgName', value: 'orgId' }"
                  :options="orgArrRow[row.key]"
                  @search="
                    (val) => {
                      handleSearchOrg(row.key, val, i);
                    }
                  "
                  @change="
                    (val) => {
                      changeOrg(row.key, val, i);
                    }
                  "
                >
                </a-select>
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.smoInfo.smoContact + '_' + i"
            >
              <template #label> SMO联系人 </template>
              <template v-if="disabled">
                {{ row.contactName || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value="row.contactName"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :colon="false"
              :name="fixedCombinationCode.smoInfo.smoPhone + '_' + i"
            >
              <template #label> SMO联系方式 </template>
              <template v-if="disabled">
                {{ row.contactPhone || '--' }}
              </template>
              <template v-else>
                <a-input
                  v-model:value="row.contactPhone"
                  :size="config.size"
                  :style="{ width: '100%' }"
                  :maxlength="200"
                  :allow-clear="true"
                  :disabled="disabled || element.options.readonlyFlag === 1"
                />
              </template>
            </a-form-item>
          </a-col>
        </template>
      </u-row>
      <div v-if="!disabled" class="btn-group">
        <u-icon
          v-if="element.options.maxCycleNumber > valueModel.length"
          name="plus-circle-fill"
          color="#0177fd"
          size="24"
          @click="addRow(i)"
        ></u-icon>
        <u-icon
          v-if="valueModel.length > 1"
          name="minus-circle-fill"
          color="#0177fd"
          size="24"
          @click="reduceRow(row.key, i)"
        ></u-icon>
        <!-- <Icon
          v-if="element.options.maxCycleNumber > valueModel.length"
          size="24"
          @click="addRow(i)"
        >
          <AddCircle color="#0177fd" />
        </Icon>
        <Icon
          v-if="valueModel.length > 1"
          size="24"
          @click="reduceRow(row.key, i)"
        >
          <RemoveCircle color="#0177fd" />
        </Icon> -->
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { PropType, ref, computed } from 'vue';
import { WidgetForm } from './config/antd';
// import { QuestionCircle16Filled } from '@vicons/fluent';
import {
  queryProfessionByOrg,
  queryPiByProfession,
  queryOrgByOrgType,
  queryMajorInResearchNum,
  queryPiInResearchNum,
} from '@/api/modules/form';
// import { RemoveCircle, AddCircle } from '@vicons/ionicons5';
import { fixedCombinationFieldCode, fixedCombinationCode } from './config/enum';
import { v4 } from 'uuid';
import { debounce } from 'lodash-es';
import { useRouter } from 'vue-router';

const router = useRouter();

const props = defineProps({
  config: {
    type: Object as PropType<WidgetForm['config']>,
    default: () => ({}),
    required: true,
  },
  element: {
    type: Object,
    default: () => ({}),
    required: true,
  },
  remoteReplace: {
    type: Object,
    default: () => ({}),
    required: true,
  },
  model: {
    type: Object,
    default: () => ({}),
    required: true,
  },
  disabled: {
    type: Boolean,
    default: true,
    required: true,
  },
  approvalPermission: {
    type: Boolean,
    default: false,
  },
});

const valueModel = computed({
  get: () => props.model[props.element.model],
  set: (val) => {
    // eslint-disable-next-line vue/no-mutating-props
    props.model[props.element.model] = val;
  },
});

const piArrRow = ref<any>({});

const initPiArr = (key, majorId, searchVal?, index?) => {
  if (props.disabled) {
    // 表单禁用，直接返回
    return;
  }
  if (!majorId) {
    // 未选择专业
    piArrRow.value[key] = [];
    return;
  }
  if (searchVal === undefined || searchVal === null || searchVal === '') {
    if (index !== undefined && index !== null) {
      // 未输入搜索条件时，以选中值的label作为搜索
      searchVal = valueModel.value[index].pi.label;
    }
  }
  const queryObj = {
    pageSize: 20,
    pageNum: 1,
    orgId: props.remoteReplace.orgId,
    majorId,
    searchVal: searchVal ?? '',
  };
  queryPiByProfession(queryObj).then((res: any) => {
    piArrRow.value[key] = res.list;
  });
};

// 所有专业选项（不同行的专业以key区分）
const professionArrRow = ref<any>({});

/**
 * 初始化专业选项
 * @param key 每行主键
 * @param searchVal 搜索条件（专业名称）
 * @param searchVal 行下标
 */
const initProfessionArr = (key, searchVal?, index?) => {
  if (props.disabled) {
    // 表单禁用，直接返回
    return;
  }
  if (searchVal === undefined || searchVal === null || searchVal === '') {
    if (index !== undefined && index !== null) {
      // 未输入搜索条件时，以选中值的label作为搜索
      searchVal = valueModel.value[index].profession.label;
    }
  }
  const queryObj = {
    pageSize: 20,
    pageNum: 1,
    orgId: props.remoteReplace.orgId,
    searchVal: searchVal ?? '',
  };
  queryProfessionByOrg(queryObj).then((res) => {
    professionArrRow.value[key] = res.list;
  });
};

const orgArrRow = ref<any>({});

const initOrgArr = (key, searchVal?, index?) => {
  if (props.disabled) {
    // 表单禁用，直接返回
    return;
  }
  const orgType = getOrgType();
  if (orgType === null) {
    // 组织类型为空，直接返回
    return;
  }
  if (searchVal === undefined || searchVal === null || searchVal === '') {
    if (index !== undefined && index !== null) {
      // 未输入搜索条件时，以选中值的label作为搜索
      searchVal = valueModel.value[index].orgInfo.label;
    }
  }
  const queryObj = {
    pageSize: 20,
    pageNum: 1,
    orgType,
    searchVal: searchVal ?? '',
  };
  queryOrgByOrgType(queryObj).then((res) => {
    orgArrRow.value[key] = res.list;
  });
};

/**
 * 增加行
 * @param index 下标
 */
const addRow = (index) => {
  const rowObj: any = {};
  rowObj.key = v4().replaceAll('-', '');
  if (props.element.fieldCode === fixedCombinationFieldCode.piInfo) {
    rowObj.profession = {};
    rowObj.pi = {};
    initProfessionArr(rowObj.key);
  } else {
    const arr = [
      fixedCombinationFieldCode.sponsorInfo,
      fixedCombinationFieldCode.croInfo,
      fixedCombinationFieldCode.smoInfo,
    ];
    if (arr.includes(props.element.fieldCode)) {
      rowObj.orgInfo = {};
      initOrgArr(rowObj.key);
    }
  }
  valueModel.value.splice(index + 1, 0, rowObj);
  if (props.element.fieldCode === fixedCombinationFieldCode.piInfo) {
    piArrRow.value[rowObj.key] = [];
  }
};

/**
 * 移除行
 * @param key 行key
 * @param index 行下标
 */
const reduceRow = (key, index) => {
  valueModel.value.splice(index, 1);
  if (props.element.fieldCode === fixedCombinationFieldCode.piInfo) {
    delete piArrRow.value[key];
  }
};

/**
 * 初始化行
 */
const initRow = () => {
  if (valueModel.value.length === 0) {
    addRow(0);
  } else {
    valueModel.value.forEach((row) => {
      row.key = v4().replaceAll('-', '');
      if (props.element.fieldCode === fixedCombinationFieldCode.piInfo) {
        piArrRow.value[row.key] = [];
        initProfessionArr(row.key, row.profession?.label);
        if (row && row.profession && row.profession.value) {
          // 初始化主要研究者选项
          initPiArr(row.key, row.profession.value);
        }
      } else {
        initOrgArr(row.key, row.orgInfo?.label);
      }
    });
  }
};

/**
 * 远程搜索专业
 */
const handleSearchProfession = debounce((key, val, i) => {
  initProfessionArr(key, val, i);
}, 500);

/**
 * 远程搜索专业下的PI
 */
const handleSearchPi = debounce((key, val, i) => {
  initPiArr(key, valueModel.value[i].profession?.value, val, i);
}, 500);

/**
 * 远程搜索组织
 */
const handleSearchOrg = debounce((key, val, i) => {
  initOrgArr(key, val, i);
}, 500);

/**
 * 根据固定组合字段编码获取组织类型
 */
const getOrgType = () => {
  if (props.element.fieldCode === fixedCombinationFieldCode.sponsorInfo) {
    return 3;
  } else if (props.element.fieldCode === fixedCombinationFieldCode.croInfo) {
    return 4;
  } else if (props.element.fieldCode === fixedCombinationFieldCode.smoInfo) {
    return 5;
  }
  return null;
};

/**
 * 专业change事件
 * @param key 行主键
 * @param val 变化后的值
 * @param index 行索引
 */
const changeProfession = (key, val, index) => {
  // 设置专业的名称
  const option = professionArrRow.value[key].find((opt) => opt.majorId === val);
  if (option) {
    valueModel.value[index].profession.label = option.majorName;
  } else {
    // 清空选项时，选项重置
    valueModel.value[index].profession.label = null;
    initProfessionArr(key);
  }
  valueModel.value[index].pi = {};
  valueModel.value[index].titleType = null;
  const majorId = valueModel.value[index].profession.value;
  if (!majorId) {
    piArrRow.value[key] = [];
    return;
  }
  // 初始化主要研究者选项
  initPiArr(key, majorId);
};

const changePi = (key, val, index) => {
  const piOpt = piArrRow.value[key].find((temp) => temp.userId === val);
  if (piOpt) {
    valueModel.value[index].pi.label = piOpt.name;
    valueModel.value[index].pi.fullLabel =
      piOpt.name + '（' + piOpt.mobile + '）';
    if (piOpt.titleType) {
      valueModel.value[index].titleType = piOpt.titleType;
    } else {
      valueModel.value[index].titleType = null;
    }
  } else {
    valueModel.value[index].titleType = null;
    // 清空选项时，选项重置
    valueModel.value[index].pi.label = null;
    initPiArr(key, valueModel.value[index].profession?.value);
  }
};

/**
 * 校验PI专业
 */
const checkPiMajor = async (_rule: any) => {
  const name = _rule.field;
  const piObj =
    valueModel.value[
      Number(name.replace(fixedCombinationCode.piInfo.piMajor + '_', ''))
    ];
  const value = piObj.profession.value;
  if (_rule.required) {
    if (value) {
      return Promise.resolve();
    }
    // 必填
    return Promise.reject('请选择本中心承担的专业');
  }
  return Promise.resolve();
};

/**
 * 校验PI名称
 */
const checkPiName = async (_rule: any) => {
  const name = _rule.field;
  const piObj =
    valueModel.value[
      Number(name.replace(fixedCombinationCode.piInfo.piName + '_', ''))
    ];
  const value = piObj.pi.value;
  if (_rule.required) {
    if (value) {
      return Promise.resolve();
    }
    // 必填
    return Promise.reject('请选择本中心主要研究者');
  }
  return Promise.resolve();
};

/**
 * 校验PI职称
 */
const checkPiTitle = async (_rule: any) => {
  const name = _rule.field;
  const piObj =
    valueModel.value[
      Number(name.replace(fixedCombinationCode.piInfo.piTitle + '_', ''))
    ];
  const value = piObj.titleType;
  if (_rule.required) {
    if (value) {
      return Promise.resolve();
    }
    // 必填
    return Promise.reject('请选择本中心主要研究者职称');
  }
  return Promise.resolve();
};

/**
 * 改变组织
 */
const changeOrg = (key, val, index) => {
  // 设置组织的名称
  const option = orgArrRow.value[key].find((opt) => opt.orgId === val);
  if (option) {
    valueModel.value[index].orgInfo.label = option.orgName;
  } else {
    // 清空选项时，选项重置
    valueModel.value[index].orgInfo.label = null;
    initOrgArr(key);
  }
};

/**
 * 校验申办方
 */
const checkSponsorOrg = async (_rule: any) => {
  const name = _rule.field;
  const sponsorInfo =
    valueModel.value[
      Number(
        name.replace(fixedCombinationCode.sponsorInfo.sponsorOrg + '_', '')
      )
    ];
  const value = sponsorInfo.orgInfo.value;
  if (_rule.required) {
    if (value) {
      return Promise.resolve();
    }
    // 必填
    return Promise.reject('请选择申办方');
  }
  return Promise.resolve();
};

/**
 * 获取pi在研项目数
 */
const piObj = ref<any>({});
const queryProjectNumByPI = async (piIds) => {
  try {
    const params = {
      piIds,
    };
    const res = await queryPiInResearchNum(params);
    piObj.value[piIds] = res;
  } catch {
    console.log('pi catch');
    piObj.value[piIds] = '111';
  }
};

/**
 * 获取专业在研项目数
 */
const majorObj = ref<any>({});
const queryProjectNumByMajor = async (majorIds) => {
  try {
    const params = {
      majorIds,
    };
    const res = await queryMajorInResearchNum(params);
    console.log(res);
    majorObj.value[majorIds] = res;
  } catch {
    console.log('major catch');
    majorObj.value[majorIds] = '222';
  }
};

const init = () => {
  if (props.disabled) {
    (valueModel.value || []).forEach((item) => {
      if (item.pi?.value) {
        queryProjectNumByPI(item.pi.value);
      }
      if (item.profession?.value) {
        queryProjectNumByMajor(item.profession.value);
      }
    });
  }
};

init();

const gotoClick = (feild, value) => {
  router.push({ path: '/projectCenter/index', query: { [feild]: value } });
};

initRow();

defineExpose({});
</script>

<style lang="scss" scoped>
:deep(.btn-group) {
  span {
    cursor: pointer;
  }
}
.project-num {
  color: $u-type-primary;
  font-style: italic;
  text-decoration: underline;
}
</style>
